package org.opu.gui.docviewer.table;

import javax.swing.text.BoxView;
import javax.swing.text.Element;
import javax.swing.text.View;


/**
 * CellView is the main one all the rest are just containers.
 * CellView has inner insets to avoid border and text overlapping.
 * We also redefine getPreferredSpan(0 method of the cell to provide
 * proper width. The width is stored as an Attribute so if measured
 * axis is X_AXIS we just extract the attribute value and return it
 * in opposite case use super call
 * 
 * @author yura
 */
public class CellView extends BoxView {

    /**
     *  Constructs a CellView, with the insets for the view (2, 2, 2, 2).
     *
     * @param elem the element this view is responsible for
     */
    public CellView(Element elem) {
        super(elem, View.Y_AXIS);
        setInsets((short) 2, (short) 2, (short) 2, (short) 2);
    }

    @Override
    public float getPreferredSpan(int axis) {
        if (axis == View.X_AXIS) {
            return getCellWidth();
        }
        return super.getPreferredSpan(axis);
    }

    @Override
    public float getMinimumSpan(int axis) {
        return getPreferredSpan(axis);
    }

    @Override
    public float getMaximumSpan(int axis) {
        return getPreferredSpan(axis);
    }

    @Override
    public float getAlignment(int axis) {
        return 0;
    }

    /**
     *  Return cell width
     *
     * @return cell width
     */
    public int getCellWidth() {
        int width = 100;
        String pwidth = TableDocument.PARAM_CELL_WIDTH;
        Integer i = (Integer) getAttributes().getAttribute(pwidth);
        if (i != null) {
            width = i.intValue();
        }
        return width;
    }
}
